package com.resys.server.controller.staff;

import com.resys.entity.dto.TokenUserInfoDto;
import com.resys.entity.dto.UserInfoDto;
import com.resys.entity.po.User;
import com.resys.entity.vo.ResponseVO;
import com.resys.exception.BusinessException;
import com.resys.mappers.UserMapper;
import com.resys.server.component.RedisComponent;
import com.resys.server.controller.ABaseController;
import com.wf.captcha.ArithmeticCaptcha;
import com.resys.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.HashMap;
import java.util.Map;

@RestController("StaffAccountController")
@RequestMapping("/staff/account")
@Api(tags = "员工模块-登录接口")
public class AccountController extends ABaseController {
    @Resource
    private UserService userService;
    @Resource
    private RedisComponent redisComponent;
    @ApiOperation("获取验证码,返回base64编码加工的图片,且五分钟内有效")
    @GetMapping("/checkCode")
    public ResponseVO checkCode(){
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(100, 42);
        String code = captcha.text();
        String checkCodeKey = redisComponent.saveCheckCode(code);
        String checkCodeBase64 = captcha.toBase64();
        Map<String,String> result = new HashMap<>();
        result.put("checkCode",checkCodeBase64);
        result.put("checkCodeKey",checkCodeKey);
        return getSuccessResponseVO(result);
    }
    @PostMapping("/register")
    @ApiOperation("注册功能接口")
    public ResponseVO register(@NotEmpty String phone,
                               @NotEmpty @Size(max = 20)String userName,
                               @NotEmpty String registerPassword,
                               String realName,
                               @NotEmpty String checkCodeKey,
                               @NotEmpty String checkCode){
        try {
            if(!checkCode.equalsIgnoreCase(redisComponent.getCheckCode(checkCodeKey))){
                throw new BusinessException("图片验证码错误");
            }
            userService.register(phone,userName,registerPassword,realName,1);
            return getSuccessResponseVO(null);
        }finally {
            redisComponent.deleteCheckCode(checkCodeKey);
        }

    }

    @ApiOperation("登录功能接口")
    @PostMapping("/login")
    public ResponseVO login(HttpServletResponse response,
                            HttpServletRequest request,
                            @NotEmpty String username,
                            @NotEmpty String password,
                            @NotEmpty String checkCodeKey,
                            @NotEmpty String checkCode) {
        try {
            if (!checkCode.equalsIgnoreCase(redisComponent.getCheckCode(checkCodeKey))) {
                throw new BusinessException("图片验证码错误");
            }
            User user = userService.getUserByUsername(username);
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            if (user == null) {
                throw new BusinessException("用户名不存在");
            } else if (user.getAccountStatus() != 0) {
                throw new BusinessException("账号已被禁用");
            } else if (!md5Password.equals(user.getPassword())) {
                throw new BusinessException("密码错误");
            } else if (user.getRole() != 1) {
                throw new BusinessException("用户不存在");
            }
            TokenUserInfoDto tokenUserInfoDto = new TokenUserInfoDto();
            tokenUserInfoDto.setUserId(user.getUserId());
            tokenUserInfoDto.setUserName(user.getUsername());
            tokenUserInfoDto.setRole(user.getRole());
            tokenUserInfoDto.setRealName(user.getRealName());
            redisComponent.saveTokenInfo(tokenUserInfoDto, "staff");
            saveToken2Cookie(response,tokenUserInfoDto.getToken(), "staff");
            return getSuccessResponseVO("登录成功");
        } finally {
            redisComponent.deleteCheckCode(checkCodeKey);

        }
    }
    @ApiOperation("自动登录功能接口")
    @GetMapping("/autoLogin")
    public ResponseVO autoLogin( HttpServletResponse response){


        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo("staff");
        if(tokenUserInfoDto == null){
            return getServerErrorResponseVO("请先登录");

        }
        if(tokenUserInfoDto.getExpireAt() - System.currentTimeMillis()<60000*60){
            redisComponent.saveTokenInfo(tokenUserInfoDto,"staff");
            saveToken2Cookie(response,tokenUserInfoDto.getToken(),"staff");
        }
        saveToken2Cookie(response,tokenUserInfoDto.getToken(),"staff");
        return getSuccessResponseVO(tokenUserInfoDto);
    }
    @ApiOperation("退出登录")
    @GetMapping("/loginout")
    public ResponseVO loginout( HttpServletResponse response){
        cleanCookie(response,"staff");
        return getSuccessResponseVO(null);
    }
    @ApiOperation("获取当前登录用户信息")
    @GetMapping
    public ResponseVO account(){
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo("staff");
        if(tokenUserInfoDto == null){
            throw new BusinessException("请先登录");
        }
        User user =userService.getUserByUserId(tokenUserInfoDto.getUserId());

        return getSuccessResponseVO(user);
    }
    @ApiOperation("修改个人信息")
    @PostMapping("/update")
    public ResponseVO update(@RequestBody UserInfoDto userInfoDto){
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo("staff");
        User user =userService.getUserByUserId(tokenUserInfoDto.getUserId());
        if(user == null){
            throw new BusinessException("用户名不存在");
        }
        if(!userInfoDto.getUsername().equals(user.getUsername())&&checkSameName(userInfoDto.getUsername(),user.getUsername())){
            throw new BusinessException("用户名已存在");
        }
        BeanUtils.copyProperties(userInfoDto,user);
        String password = userInfoDto.getPassword();
        if(password != null){
            user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        }else {
            user.setPassword(tokenUserInfoDto.getPassword());
        }
        userService.updateUserByUserId(user,user.getUserId());
        return getSuccessResponseVO("修改成功");
    }


}
